const express = require("express");
// 引入vue app实例
import createApp from "../app";
// 引入渲染html的方法
import { renderToString } from "vue/server-renderer";
// 引入路由
import createRouter from "../router";
// 引入挂在路由的方法 node方式
import { createMemoryHistory } from "vue-router";

const server = express();

// express 部署静态资源
server.use(express.static("build"));

// 任一路径都可以访问到路由
server.get("/*", async (req, res) => {
    // 实例化app
    const app = createApp();

    // app 安装路由插件
    let router = createRouter(createMemoryHistory());
    app.use(router);
    await router.push(req.url || "/"); // 跳转路由  目标路径或者主页
    await router.isReady(); // 等待异步路由加载完成 再渲染页面  这两个方法异步

    // 服务器编译html
    const appStringHtml = await renderToString(app);

    const htmlString = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <h1>Vue3 Serve Side Render</h1>
      <div id="app">
        ${appStringHtml}
      </div>
      // 这里用script标签引入打包后的客户端代码
      <script src="/client/client_bundle.js"></script>
    </body>
    </html>
    `;

    res.send(htmlString);
});

server.listen(5506, () => {
    console.log(`5506 服务已启动~`);
});
